<template>
  <NavBar title="任务中心" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="task-center-container">
    <!-- 主横幅 -->
    <view class="hero-banner">
		<image class="banner-content" src="/static/renwu.png" mode=""></image>
  
    </view>
    
    <!-- 任务列表 -->
    <view class="task-list">
      <!-- 任务1: 看广告得金豆 -->
      <view class="task-card">
        <view class="task-icon">
          <image class="icon-play" src="/static/tack2.png" mode=""></image>
        </view>
        <view class="task-content">
          <view class="task-title-row">
            <view class="task-title">看广告得金豆
			<image class="reward-icon" src="/static/svip9.png" mode=""></image>
			<text class="reward-amount">+{{ taskConfig.reward_beans }}</text>
			</view>
           
          </view>
          <text class="task-desc">每天可完成{{ taskConfig.reward_daily_limit }}次</text>
        </view>
        <button class="task-btn" @tap="watchAd">立即观看</button>
      </view>
      
      <!-- 任务2: 邀请好友得金豆 -->
      <view class="task-card">
        <view class="task-icon">
          <image class="icon-play" src="/static/tack3.png" mode=""></image>
        </view>
        <view class="task-content">
          <view class="task-title-row">
            <view class="task-title">邀请好友得金豆
			<image class="reward-icon" src="/static/svip9.png" mode=""></image>
			<text class="reward-amount">+{{ taskConfig.reward_beans }}</text>
			</view>
          </view>
          <text class="task-desc">每天可完成1次</text>
        </view>
        <button
          class="task-btn"
          :open-type="isWeixinMP ? 'share' : ''"
          @tap="!isWeixinMP ? goToInvite() : null"
        >
          去邀请
        </button>
      </view>
      
      <!-- 任务3: 好友购买资源包得海量金豆 -->
      <view class="task-card">
        <view class="task-icon">
          <image class="icon-play" src="/static/tack4.png" mode=""></image>
        </view>
        <view class="task-content">
          <view class="task-title-row">
            <view class="task-title">好友购买资源包得海量金豆
			<image class="reward-icon" src="/static/svip9.png" mode=""></image>
			<text class="reward-amount">+{{ taskConfig.reward_beans }}</text>
			</view>
          </view>
          <text class="task-desc">好友购买资源包,根据购买资源...</text>
        </view>
        <button
          class="task-btn"
          :open-type="isWeixinMP ? 'share' : ''"
          @tap="!isWeixinMP ? goToInvite() : null"
        >
          去邀请
        </button>
      </view>
      
      <!-- 任务4: 好友激活SVIP卡得金豆 -->
      <view class="task-card">
        <view class="task-icon">
         <image class="icon-play" src="/static/tack5.png" mode=""></image>
        </view>
        <view class="task-content">
          <view class="task-title-row">
            <text class="task-title">好友激活SVIP卡得金豆</text>
         
          </view>
          <text class="task-desc">好友激活SVIP卡得金豆</text>
        </view>
        <button
          class="task-btn"
          :open-type="isWeixinMP ? 'share' : ''"
          @tap="!isWeixinMP ? goToInvite() : null"
        >
          去邀请
        </button>
      </view>
      
      <!-- 任务5: 金豆兑换红包 -->
      <view class="task-card">
        <view class="task-icon">
          <image class="icon-play" src="/static/tack6.png" mode=""></image>
        </view>
        <view class="task-content">
          <view class="task-title-row">
            <text class="task-title">金豆兑换红包</text>
         
          </view>
          <text class="task-desc">金豆可兑换搜题次数或兑换红包</text>
        </view>
        <button class="task-btn" @tap="showExchangeModal">去兑换</button>
      </view>
    </view>
    
    <!-- 金豆兑换弹窗 -->
    <GoldBeanExchange
      ref="goldBeanExchangeRef"
      :userBalance="userGoldBeans"
      @close="hideExchangeModal"
      @exchange="handleExchange"
    />

    <!-- 领取奖励成功弹窗 -->
    <CommonPopup
      ref="successPopup"
      :title="popupTitle"
      :message="popupMessage"
      :type="popupType"
    />
  </view>
  </NavBar>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onShareAppMessage } from '@dcloudio/uni-app'
import { getTaskConfig } from '../../utils/config.js'
import { getCurrentUser, getToken, fetchUserInfo } from '../../utils/user.js'
import { isWeixinMiniProgram } from '../../utils/platform.js'
import { AD_API } from '../../config/api.js'
import { makeMagicToken } from '../../config/magic.js'
import GoldBeanExchange from '../../components/GoldBeanExchange/GoldBeanExchange.vue'
import CommonPopup from '@/components/CommonPopup/CommonPopup.vue'

// 响应式数据
const currentTask = ref(0)
const userGoldBeans = ref(1879837987)
const goldBeanExchangeRef = ref()
const successPopup = ref(null)
const taskConfig = ref({
  reward_beans: 10,
  reward_daily_limit: 6,
  invite_beancoin: 5
})

// 弹窗控制数据
const popupTitle = ref('获得奖励')
const popupMessage = ref('恭喜获得金豆')
const popupType = ref('success')

// 平台判断
const isWeixinMP = computed(() => isWeixinMiniProgram())

// 方法
const goBack = () => {
  uni.navigateBack()
}

const handleTask = (taskIndex: number) => {
  currentTask.value = taskIndex
  console.log(`执行任务 ${taskIndex}`)
  
  // 根据任务类型执行不同操作
  switch (taskIndex) {
    case 0:
      uni.showToast({
        title: '开始观看广告',
        icon: 'none'
      })
      break
    case 1:
      goToInvite()
      break
    case 2:
      goToPurchaseResource()
      break
    case 3:
      goToVip()
      break
    case 4:
      showExchangeModal()
      break
  }
}

// 金豆兑换相关方法
const showExchangeModal = () => {
  goldBeanExchangeRef.value?.open()
}

const hideExchangeModal = () => {
  goldBeanExchangeRef.value?.close()
}

const handleExchange = (data: { beans: number, yuan: number, alipayIndex: number }) => {
  console.log('兑换数据:', data)
  // 这里可以添加实际的兑换逻辑
  // 比如调用API接口进行兑换
}

// 观看广告相关方法
const watchAd = async () => {
  // 显示敬请期待提示
  uni.showToast({
    title: '敬请期待',
    icon: 'none'
  })
  return;
  // 原本的广告逻辑
  try {
    // 判断平台类型
    const adType = isWeixinMP.value ? 1 : 2 // 1=微信激励视频, 2=uni激励视频

    console.log('开始观看广告，平台类型:', adType)

    // 调用激励视频API
    await callRewardVideoAPI(adType)
  } catch (error) {
    console.error('观看广告失败:', error)
    uni.showToast({
      title: error.message || '观看广告失败',
      icon: 'error'
    })
  }
}

// 调用激励视频API
const callRewardVideoAPI = async (adType) => {
  try {
    // 获取token
    const token = getToken()
    if (!token) {
      uni.showToast({
        title: '请先登录',
        icon: 'error'
      })
      return
    }

    console.log('调用激励视频API，参数:', { ad_type: adType })

    uni.showLoading({
      title: '获取广告中...'
    })

    // 发起API请求
    const response = await uni.request({
      url: AD_API.REWARD,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      data: {
        ad_type: adType
      }
    })

    uni.hideLoading()
    console.log('激励视频API响应:', response)

    // 检查响应状态
    if (response.statusCode === 200 && response.data.code === 200) {
      // 调用成功处理函数
      onRewardVideoSuccess(response.data)
    } else {
      throw new Error(response.data?.data?.error_message || response.data?.message || `请求失败，状态码: ${response.statusCode}`)
    }

  } catch (error) {
    uni.hideLoading()
    console.error('调用激励视频API失败:', error)
    throw error
  }
}

// 激励视频请求成功回调函数
const onRewardVideoSuccess = (responseData) => {
  console.log('=== 激励视频请求成功 ===')
  console.log('响应数据:', responseData)
  console.log('请求时间:', new Date().toLocaleString())
  console.log('平台类型:', isWeixinMP.value ? '微信小程序' : 'APP')

  // 显示成功提示
  uni.showToast({
    title: '激励视频请求成功',
    icon: 'success',
    duration: 2000
  })

  // 检查响应数据中是否包含必要的字段
  if (responseData && responseData.data && responseData.data.nonce && responseData.data.voice_sign) {
    console.log('检测到奖励数据，20秒后自动领取奖励...')
    console.log('nonce:', responseData.data.nonce)
    console.log('voice_sign:', responseData.data.voice_sign)

    // 20秒后调用领取奖励接口
    setTimeout(() => {
      claimReward(responseData.data.nonce, responseData.data.voice_sign)
    }, 20000) // 20秒 = 20000毫秒

    // 显示倒计时提示
    uni.showToast({
      title: '20秒后自动领取奖励',
      icon: 'none',
      duration: 3000
    })
  } else {
    console.warn('响应数据中缺少必要的奖励字段')
  }

  console.log('=== 激励视频请求成功处理完成 ===')
}

// 领取激励奖励
const claimReward = async (nonce, voiceSign) => {
  try {
    console.log('=== 开始领取激励奖励 ===')
    console.log('nonce:', nonce)
    console.log('voice_sign:', voiceSign)

    // 获取原始token
    const originalToken = getToken()
    if (!originalToken) {
      console.error('未找到token，无法领取奖励')
      uni.showToast({
        title: '请先登录',
        icon: 'error'
      })
      return
    }

    // 检查token长度和voice_sign长度
    if (originalToken.length !== 256) {
      console.error('token长度不正确，期望256，实际:', originalToken.length)
      uni.showToast({
        title: 'token格式错误',
        icon: 'error'
      })
      return
    }

    if (voiceSign.length !== 5) {
      console.error('voice_sign长度不正确，期望5，实际:', voiceSign.length)
      uni.showToast({
        title: '签名格式错误',
        icon: 'error'
      })
      return
    }

    // 使用magic函数处理token
    console.log('开始处理token...')
    const magicToken = makeMagicToken(originalToken, voiceSign)
    console.log('token处理完成')

    uni.showLoading({
      title: '领取奖励中...'
    })

    // 发起领取奖励请求
    console.log('发起领取奖励请求...')
    const response = await uni.request({
      url: AD_API.CLAIM,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${magicToken}`
      },
      data: {
        nonce: nonce,
        voice_sign: voiceSign
      }
    })

    uni.hideLoading()
    console.log('领取奖励API响应:', response)

    // 检查响应状态
    if (response.statusCode === 200 && response.data.code === 200) {
      console.log('奖励领取成功:', response.data)

      // 设置弹窗内容
      popupTitle.value = '获得奖励'
      popupMessage.value = `恭喜获得${taskConfig.value.reward_beans}金豆。`
      popupType.value = 'success'

      // 显示弹窗
      successPopup.value.show()

      // 刷新用户信息以更新金豆数量
      try {
        await fetchUserInfo()
        console.log('用户信息刷新成功')
      } catch (error) {
        console.error('刷新用户信息失败:', error)
      }
    } else {
      throw new Error(response.data?.data?.error_message || response.data?.message || `领取失败，状态码: ${response.statusCode}`)
    }

  } catch (error) {
    uni.hideLoading()
    console.error('=== 领取激励奖励失败 ===')
    console.error('错误详情:', error)
    uni.showToast({
      title: error.message || '领取失败',
      icon: 'error'
    })
  }

  console.log('=== 领取激励奖励流程结束 ===')
}

// 邀请好友相关方法（仅用于非微信小程序平台）
const goToInvite = () => {
  // 其他平台跳转到邀请好友记录页面
  uni.navigateTo({
    url: '/pages/invite-friends/invite-friends'
  })
}



// 购买资源包相关方法
const goToPurchaseResource = () => {
  uni.navigateTo({
    url: '/pages/purchase-resource/purchase-resource'
  })
}

// VIP相关方法
const goToVip = () => {
  uni.navigateTo({
    url: '/pages/vip/vip'
  })
}

// 获取任务配置
const fetchTaskConfig = async () => {
  try {
    const config = await getTaskConfig(true)
    taskConfig.value = {
      reward_beans: config.reward_beans || 10,
      reward_daily_limit: config.reward_daily_limit || 6,
      invite_beancoin: config.invite_beancoin || 5
    }
    console.log('任务配置更新:', taskConfig.value)
  } catch (error) {
    console.error('获取任务配置失败:', error)
    // 使用默认配置
    taskConfig.value = {
      reward_beans: 10,
      reward_daily_limit: 6,
      invite_beancoin: 5
    }
  }
}

// 页面加载时初始化
onMounted(() => {
  console.log('任务中心页面加载')
  fetchTaskConfig()
})

// 微信分享配置
// #ifdef MP-WEIXIN
onShareAppMessage((res) => {
  console.log('分享触发:', res)

  const user = getCurrentUser()
  const userid = user?.userid || ''

  return {
    title: '邀请你一起使用solve拍照搜题',
    path: `/pages/index/index?inviter_id=${userid}`,
    imageUrl: '/static/profile/avatar.jpg' // 分享图片
  }
})
// #endif
</script>

<style scoped>
.task-center-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #E3F2FD 0%, #F5F5F5 100%);
  position: relative;
  background: linear-gradient( 180deg, #C2DDFF 0%, #F3F5FE 100%);
border-radius: 0rpx 0rpx 0rpx 0rpx;
padding-top: 200rpx;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx 10rpx;
  background: white;
}

.status-time {
  font-size: 34rpx;
  font-weight: 600;
  color: #000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.status-icon {
  font-size: 24rpx;
  color: #000;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx;
  background: #E3F2FD;
}

.back-button {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 32rpx;
  color: #666;
  font-weight: bold;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.nav-placeholder {
  width: 60rpx;
  height: 60rpx;
  background: white;
  border-radius: 30rpx;
}

/* 主横幅 */
.hero-banner {
  margin: 0 20rpx;
}

.banner-content {
  height: 354rpx;
  width: 100%;
}

.banner-left {
  flex: 1;
}

.banner-title {
  font-size: 48rpx;
  font-weight: 800;
  color: white;
  display: block;
  margin-bottom: 10rpx;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  line-height: 1.2;
}

.banner-highlight {
  font-size: 48rpx;
  font-weight: 800;
  color: #FFD700;
  display: inline;
  text-shadow: 0 2rpx 4rpx rgba(255, 215, 0, 0.3);
}

.banner-right {
  position: relative;
}

.robot-character {
  position: relative;
  width: 140rpx;
  height: 140rpx;
}

.robot-head {
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #9C27B0 0%, #7B1FA2 100%);
  border-radius: 50rpx;
  position: relative;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.robot-screen {
  width: 60rpx;
  height: 40rpx;
  background: #2196F3;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dollar-signs {
  font-size: 24rpx;
  color: white;
  font-weight: bold;
}

.robot-body {
  width: 80rpx;
  height: 30rpx;
  background: linear-gradient(135deg, #9C27B0 0%, #7B1FA2 100%);
  border-radius: 15rpx;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: -5rpx;
}

.robot-x {
  font-size: 24rpx;
  color: white;
  font-weight: bold;
}

.robot-envelope {
  position: absolute;
  top: 20rpx;
  right: -20rpx;
  width: 40rpx;
  height: 40rpx;
  background: #F44336;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 8rpx rgba(244, 67, 54, 0.3);
}

.envelope-icon {
  font-size: 20rpx;
}

.floating-coins {
  position: absolute;
  top: 10rpx;
  left: -30rpx;
}

.floating-envelopes {
  position: absolute;
  bottom: 20rpx;
  right: -40rpx;
}

.coin, .envelope {
  font-size: 16rpx;
  display: block;
  margin-bottom: 8rpx;
  animation: float 2s ease-in-out infinite;
}

.envelope {
  animation-delay: 1s;
}

@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10rpx); }
}

.banner-info {
  background: white;
  border: 2rpx solid #FF4081;
  border-radius: 16rpx;
  padding: 16rpx 24rpx;
  text-align: center;
  position: relative;
  z-index: 2;
}
.icon-play{
	width: 96rpx;
	height: 96rpx;
}
.info-text {
  font-size: 24rpx;
  color: #333;
  font-weight: 500;
}

/* 任务列表 */
.task-list {
  padding: 30rpx;
}

.task-card {
background: #F5F6FA;
border-radius: 16rpx 16rpx 16rpx 16rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.task-card:active {
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.12);
}

.task-icon {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  margin-right: 24rpx;

}

.icon-play, .icon-invite, .icon-crown, .icon-card, .icon-exchange {
  font-size: 32rpx;
  color: white;
}

.task-content {
  flex: 1;
  margin-right: 20rpx;
}

.task-title-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.task-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 16rpx;
}

.task-reward {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.reward-icon {
  width: 27rpx;
  height: 25rpx;
  margin-left: 5rpx;
}

.reward-amount {
  font-size: 24rpx;
  font-weight: 700;
  margin-left: 5rpx;
}

.task-desc {
  font-size: 24rpx;
  color: #666;
  height: 30rpx;
   overflow: hidden; /* 隐藏溢出的内容 */
      text-overflow: ellipsis; /* 显示省略号 */
      white-space: nowrap; /* 防止文本换行 */
}

.task-btn {
width: 162rpx;
font-weight: 500;
font-size: 24rpx;
color: #FFFFFF;
text-align: center;
font-style: normal;
text-transform: none;
 height: 48rpx;
 line-height: 48rpx;
background: linear-gradient( 270deg, #91BEF8 0%, #4593FA 100%);
border-radius: 24rpx 24rpx 24rpx 24rpx;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.task-btn:active {
  background: #1976D2;
  transform: scale(0.95);
}
</style>
